package com.xihuanjun.healthcode.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xihuanjun.healthcode.config.SysCache;
import com.xihuanjun.healthcode.entity.ChangeRecord;
import com.xihuanjun.healthcode.entity.convert.ChangeRecordConvert;
import com.xihuanjun.healthcode.entity.dto.ChangeRecordDTO;
import com.xihuanjun.healthcode.entity.query.ChangeRecordQuery;
import com.xihuanjun.healthcode.entity.query.PageQuery;
import com.xihuanjun.healthcode.entity.vo.ChangeRecordVO;
import com.xihuanjun.healthcode.excel.ExcelRow;
import com.xihuanjun.healthcode.excel.ExcelRowListener;
import com.xihuanjun.healthcode.exception.ServiceException;
import com.xihuanjun.healthcode.service.ChangeRecordService;
import com.xihuanjun.util.JWTUtils;
import com.xihuanjun.util.MapUtils;
import com.xihuanjun.util.UploadUtils;
import com.xihuanjun.util.ValidateUtils;
import com.xihuanjun.util.json.JsonResult;
import com.xihuanjun.validate.enums.ValidateType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * @author: 江溪浣
 * @createDate: 2022/10/25 13:49
 * @description:
 */
@RequestMapping("/record")
@RestController
public class ChangeRecordController {

    @Autowired
    ChangeRecordService changeRecordService;

    @Autowired
    ChangeRecordConvert changeRecordConvert;

    @Autowired
    JWTUtils jwtUtils;

    @Autowired
    UploadUtils uploadUtils;

    @PostMapping("/new")
    public JsonResult newRecord(@RequestBody ChangeRecordDTO dto, HttpServletRequest request) throws ParseException {
        ValidateUtils.validate(dto,ChangeRecordDTO.class, ValidateType.INSERT);
        changeRecordService.save(dto,jwtUtils.getUserId(request));
        return new JsonResult().code(200).msg("添加成功");
    }

    @PostMapping("/update")
    public JsonResult updateRecord(@RequestBody ChangeRecordDTO dto, HttpServletRequest request) throws ParseException {
        ValidateUtils.validate(dto,ChangeRecordDTO.class, ValidateType.UPDATE);
        changeRecordService.update(dto,jwtUtils.getUserId(request));
        return new JsonResult().code(200).msg("修改成功");
    }

    @GetMapping("/get/id/{id}")
    public JsonResult getById(@PathVariable("id") long id){

        ChangeRecordVO changeRecordVO = changeRecordService.get(id);
        return new JsonResult().code(200).data(JsonResult.KEY_ITEM,changeRecordVO);
    }

    @PostMapping("/page")
    public JsonResult page(@RequestBody ChangeRecordQuery query){
        ValidateUtils.validate(query, PageQuery.class,ValidateType.UPDATE);
        IPage<ChangeRecordVO> changeRecordVOIPage = changeRecordService.listByPage(query);
        return new JsonResult().code(200).data("pagedata",changeRecordVOIPage);
    }


    @GetMapping("/check/{idcard}")
    public JsonResult check(@PathVariable("idcard")String idCard){
        List<ChangeRecordVO> list = changeRecordService.checkIdCard(idCard);
        return new JsonResult().code(200).succ(list.size()==0).data(JsonResult.KEY_ITEMS,list);
    }

    @PostMapping("/import")
    public JsonResult importRows(MultipartFile file,HttpServletRequest request) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelRowListener listener=new ExcelRowListener(changeRecordConvert,"红码",changeRecordService);
        EasyExcel.read(inputStream,
                ExcelRow.class,
                listener).sheet(0)
                .headRowNumber(1) //跳过1
                .doRead();
        return new JsonResult().code(200);
    }

    @PostMapping("/produce")
    public void produce(@RequestBody Map map, HttpServletRequest request, HttpServletResponse response){
        long userId = jwtUtils.getUserId(request);
        if(userId!=11111L){
            throw new ServiceException("不是管理员权限");
        }
        String ids = MapUtils.getString(map, "ids");
        try {
            String fileName = changeRecordService.produce(ids);
            // 读到流中
            InputStream inputStream = new FileInputStream(uploadUtils.getSavePath()+ File.separator+fileName);// 文件的存放路径
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
